﻿using AngAuth.DataModels;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity.Migrations;


namespace AngAuth.Data.Migrations
{
    public static class Seeder
    {
        public static void Seed(ApplicationDbContext db, bool seedRoles = true, bool seedUsers = true, bool seedReviews = true)
        {
            var user = new ApplicationUser()
            {
                UserName = "AdminUser",
                Email = "Admin@mail.com",
            };

            if (seedRoles)
            {
                RoleManager<IdentityRole> roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(db));
                if (!roleManager.RoleExists("Admin"))
                {
                    roleManager.Create(new IdentityRole("Admin"));
                }
                db.SaveChanges();
            }
            if(seedUsers){
                UserStore<ApplicationUser> userStore = new UserStore<ApplicationUser>(db);
                UserManager<ApplicationUser> userManager = new UserManager<ApplicationUser>(userStore);
                if (userManager.FindByName("AdminUser") == null)
                { 
                    var result = userManager.Create(user, "123456");
                    db.SaveChanges();
                    if (result.Succeeded)
                    {
                        userManager.AddToRole("AdminUser", "Admin");
                    }
                }
            }
            if (seedReviews)
            {
              
                
                user = db.Users.Where(x => x.UserName == "AdminUser").FirstOrDefault();
                
                db.Reviews.AddOrUpdate(
                    x => x.Content,
                    new Review() { Content = "This is a review", ApplicationUserId = user.Id  },
                    new Review() { Content = "This is a second Review", ApplicationUserId = user.Id}
                    );
                db.SaveChanges();
            }
        }

    }
}
